<template>
  <page-header-wrapper>
    <a-spin :spinning="spinning">
      <a-card>
        <p class="info">基本信息</p>
        <div v-if="this.$route.query.status != 2" class="flex justify-end">
          <a-button v-if="!!id && readOnly" type="primary" @click="readOnly = false" v-action:update>修改</a-button>
          <a-button v-else type="primary" @click="submit">保存</a-button>
        </div>
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :hideRequiredMark="true"
        >
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="项目地址：" prop="projectId" v-if="!$route.query.id">
                <a-select
                  show-search
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  @change="Onchange"
                  v-model="form.projectId"
                >
                  <a-select-option :value="item.id" v-for="item in projectList" :key="item.id">
                    {{ item.addr }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="项目地址：" v-else>
                <a-input v-model="choose.addr" style="width:150px" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="客户名称：">
                <a-input :value="form.clientName" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="阶段：">
                <a-input v-model="form.stage" disabled />
                <a-modal v-model="visible" :footer="null">
                  <div class="mt-4">
                    <p>
                      您选择的项目是首次放款
                    </p>
                    <p>
                      请提前至【资金管理-项目列表-项目细节】中<a @click="toDetail">设置</a>贷款限额费、手续费等生效日期
                    </p>
                    <p>请提前至【项目完成协议】中<a @click="toAgree">设置</a>合同签订日期</p>
                    <p>若已设置请忽略</p>
                  </div>
                  <!-- <template slot="footer">
                    <a-button type="primary" @click="toDetail">
                      去设置
                    </a-button>
                    <a-button type="primary" @click="onOk">
                      确定
                    </a-button>
                  </template> -->
                </a-modal>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="律师：">
                <a-input :value="form.lawyerName" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="提款日期：" prop="date">
                <a-date-picker v-model="form.date" :disabled="readOnly && !!id" :disabled-date="disabledDate" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="计算日期：" prop="calcDate">
                <a-date-picker v-model="form.calcDate" :disabled="readOnly && !!id" :disabled-date="disabledDate" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="金额：" prop="amount">
                <m-input-number
                  v-model="form.amount"
                  :max="maxCount"
                  :disabled="readOnly && !!id"
                  style="width:200px"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="货币：">
                <a-input v-model="form.currency" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="性质：" prop="nature">
                <a-textarea v-model="form.nature" class="text" :rows="4" :disabled="readOnly && !!id" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>
    </a-spin>
  </page-header-wrapper>
</template>
<script>
import {
  createWithdraw,
  getList,
  getProjectById,
  getWithdrawSingle,
  reviseWithdraw,
  getAddr,
  getWithdraw
} from '@/api/common'
import moment from 'moment'
import { commonRule, dateRule } from '@/utils/rules'
export default {
  name: 'addWithdraw',
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 17 },
      spinning: false,
      projectList: [],
      choose: {},
      projectId: '',
      id: '',
      status: '',
      stage: '',
      maxCount: 9999999999,
      readOnly: true,
      visible: false,
      agreementDate: null,
      start: null,
      end: null,
      list: {},
      form: {
        projectId: '',
        clientName: '',
        stage: '',
        lawyerName: '',
        currency: '',
        date: null,
        calcDate: null,
        amount: '',
        nature: ''
      },
      rules: {
        projectId: commonRule,
        date: dateRule,
        calcDate: dateRule,
        amount: commonRule,
        nature: commonRule
      },
      pagination: {
        total: 1,
        pageSize: 999,
        onChange: this.getData
      }
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    form: {
      handler(v) {
        const _form = Object.assign({}, this.form)
        // console.log(_form)
        _form.date = _form.date ? _form.date.format('X') : null
        _form.calcDate = _form.calcDate ? _form.calcDate.format('X') : null
        this.$store.commit('form/SAVE_DATA', {
          key: 'addWithdraw',
          value: _form
        })
      },
      deep: true
    }
  },
  methods: {
    async init() {
      await this.getData()
      if (this.$route.query.id) {
        await this.Onchange(this.$route.query.id)
      } else {
        const formStore = this.$store.state.form?.['addWithdraw']
        if (formStore) {
          formStore.date && (formStore.date = moment(formStore.date, 'X'))
          formStore.calcDate && (formStore.calcDate = moment(formStore.calcDate, 'X'))
          formStore && Object.assign(this.form, formStore)
          if (this.form.projectId) {
            await this.Onchange(this.form.projectId)
          }
        }
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    disabledDate(endValue) {
      if (this.stage == 1) {
        const startValue = this.agreementDate
        // startValue
        if (!endValue || !startValue) {
          return false
        }
        return startValue.valueOf() >= endValue.valueOf()
      } else {
        if (!endValue || !this.start || !this.end) {
          return false
        }
        const start = this.start
        const end = this.end
        // console.log(this.start, this.end)
        return start.valueOf() >= endValue.valueOf() || end.valueOf() + 24 * 3600 * 1000 <= endValue.valueOf()
      }
    },
    change() {
      this.readOnly = false
    },
    async Onchange(v) {
      this.spinning = true
      if (this.$route.query.id) {
        const form = {
          page: 1,
          limit: 1,
          projectIds: v
        }
        const resTime = await getList(form)
        const Time = resTime.result.data.list[0]
        if (this.stage != 1) {
          let d1 = moment(Date.now() * 1000)
          let d2 = Time?.firstLoanTime ? moment(Time.firstLoanTime * 1000) : null
          if (new Date(d1).getTime() > new Date(d2).getTime()) {
            this.start = d2
          } else {
            this.start = d1
          }
          this.end = Time?.realEndTime
            ? moment(Time.realEndTime * 1000)
            : Time?.sysEndTime
            ? moment(Time.sysEndTime * 1000)
            : null
          // console.log(this.start, this.end)
        } else {
          this.agreementDate = Time?.agreementDate ? moment(Time.agreementDate * 1000) : null
          // console.log(this.agreementDate)
        }
      } else {
        this.choose = this.projectList.find(el => el.id == v)
        this.projectId = this.choose.id
        // console.log(this.choose.id)
        this.form.projectId = this.choose.id
        this.form.clientName = this.choose.clientName
        this.form.lawyerName = this.choose.lawyerName
        this.form.currency = this.choose.loanData?.currency || this.choose.currency
        var res = await getProjectById(this.projectId)
        const data = res.result.data
        this.stage = data.perid
        this.form.stage = data.perid
        if (this.stage == 1) {
          this.visible = true
        }
        const form = {
          page: 1,
          limit: 1,
          projectIds: this.projectId
        }
        const resTime = await getList(form)
        const Time = resTime.result.data.list[0]
        if (this.stage != 1) {
          let d1 = moment(Date.now())
          // console.log(d1)
          let d2 = Time.firstLoanTime ? moment(Time.firstLoanTime * 1000) : null
          if (new Date(d1).getTime() > new Date(d2).getTime()) {
            this.start = d1
          } else {
            this.start = d2
          }
          this.end = Time.realEndTime
            ? moment(Time.realEndTime * 1000)
            : Time.sysEndTime
            ? moment(Time.sysEndTime * 1000)
            : null
          // console.log(this.start, this.end)
        } else {
          this.agreementDate = Time.agreementDate ? moment(Time.agreementDate * 1000) : null
          // console.log(this.agreementDate)
        }
        const _form = {
          projectId: this.projectId,
          page: 1,
          limit: 1,
          status: 2
        }
        const count = await getWithdraw(_form)
        const _data = count.result.data
        if (_data.principal && _data.NZD) {
          this.maxCount = _data.principal - _data.NZD
        } else if (_data.principal && _data.CAD) {
          this.maxCount = _data.principal - _data.CAD
        } else {
          this.maxCount = 9999999999
        }
      }
      this.spinning = false
    },
    toDetail() {
      this.$router.push({ name: 'manage/detail', query: { id: this.projectId } })
    },
    toAgree() {
      this.$router.push({ name: 'operation', query: { id: this.projectId } })
    },
    // onOk() {
    //   this.visible = false
    // },
    async submit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let _form = Object.assign({}, this.form)
          // _form.projectId = this.projectId
          // _form.stage = this.stage
          // _form.currency = this.choose.loanData?.currency || this.choose.currency
          delete _form.clientName
          delete _form.lawyerName
          _form.date = moment(this.form.date)
            .startOf('day')
            .format('X')
          _form.calcDate = moment(this.form.calcDate)
            .startOf('day')
            .format('X')
          if (this.id) {
            // console.log(_form)
            // console.log(this.id)
            delete _form.projectId
            await reviseWithdraw(this.id, _form)
            this.$router.back(-1)
          } else {
            const res = await createWithdraw(_form)
            this.$store.commit('form/CLEAR', 'addWithdraw')
            if (!res.result.data) this.$message.error('您选择的项目还有未完成的提款请求，请先完成')
            else this.$router.back(-1)
          }
        }
      })
    },
    async getData(page = 1) {
      this.id = false
      this.status = ''
      this.projectList = []

      if (this.$route.query.id) {
        this.id = this.$route.query.id
        const res = await getWithdrawSingle(this.id)
        const _form = res.result.data
        this.status = _form.status
        for (let k in this.form) {
          this.form[k] = _form[k]
        }
        this.form.date = moment(this.form.date, 'X')
        this.form.calcDate = moment(this.form.calcDate, 'X')
        this.choose.addr = _form.addr
        // this.choose.clientName = _form.clientName
        // this.choose.currency = _form.currency
        // this.choose.lawyerName = _form.lawyerName
        this.stage = _form.stage
      } else {
        // const res = await getAddr()
        // this.projectList = res.result.data
        var _form = {
          dataType: 2,
          approve: 2,
          asseApprove: 2,
          nzApprove: 2,
          page,
          limit: this.pagination.pageSize
        }
        const res = await getList(_form)
        var newData = res.result.data.list
        this.projectList = newData.filter(el => el.agreementDate != 0 && el.Archive == 0)
      }
    }
  }
}
</script>
<style lang="css" scoped>
.info {
  border-left: 2px solid #1890ff;
  padding-left: 10px;
  font-size: 25px;
  /* margin-left: 50px; */
  margin: 20px 0;
  margin-left: 50px;
}
.text {
  resize: unset;
  vertical-align: top;
}
</style>
